<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
	private $passportClass;
	
	public function __construct(){  
        parent::__construct();
        $this->load->library('passPort');
        $this->passportClass = $this->passport;
        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
    }

	public function index()
	{	
		$get = $this->input->get();
		$this->load->config('cfd');
		$redirect = isset($get['redirect'])?$get['redirect']:'/';
		$user_info = $this->passportClass->checkCookieAuthCode('','',true);

		//加载CFD操作类
		$this->load->library('cfdClass');

		//获取产品列表
		$this->load->model('product_model');
		$productList = $this->product_model->getProduct(array('status'=>1,'platform'=>'IB'),'all','stype DESC');
		$productArr = array();
		if(!empty($productList)) foreach($productList as $product){
			$dst = $this->cfdclass->checkDST($product['name']);
			// echo $product['name']." = ".$dst."<br>";
			$settlementArr = explode(',',$product['settlement']);
			$product['settlement'] = $settlementArr[$dst];
			$productArr[$product['stype']][$product['name']] = $product;
		}
		$positionArr = array();
		$ykArr = array();//根据产品来
		if(!empty($user_info)){
			if($redirect!='/'){
				redirect($redirect);
			}
			//获取持仓信息
			$this->load->model('cfd_model');
			$positionList = $this->cfd_model->getPosition(array('uid'=>$user_info['uid'],'flag'=>0),'all','id DESC');
			if(!empty($positionList)) foreach($positionList as &$position){
				if(!$this->cfdclass->setProduct($position['name'],'IB')){//设置产品
					continue;
				}
				if(!$this->cfdclass->setDenom($position['dtype'])){//设置计价方式
					continue;
				}
				$redisData = $this->cfdclass->redisAllData();
				$lastest_price = isset($redisData['trade']['LAST_PRICE']) ? $redisData['trade']['LAST_PRICE'] : 0;
				$position['total'] = bcadd($position['num'],$position['block_num']);
				$position['margin'] = del0($this->cfdclass->countBZJ($position['total'], $position['times'], $position['additional']));
				// echo $lastest_price.",".$position['price'].",".$position['total'].",".$position['bs'].",".$position['commission'].",".$position['overnight'];
				// echo "<br>";
				$position['yk'] = del0($this->cfdclass->countYK($lastest_price,$position['price'],$position['total'],$position['bs'],$position['commission'],$position['overnight']));
				$position['ykl'] = $this->cfdclass->countYKL($position['yk'], $position['margin']);
				$position['fee'] = $this->cfdclass->countTotalFee(bcadd($position['commission'],$position['overnight'],8),$position['total']);
				$position['price'] = del0($position['price']);
				$positionArr[$position['name']][] = $position;
				$ykArr[$position['name']]['zyk'] = isset($ykArr[$position['name']]['zyk'])?bcadd($ykArr[$position['name']]['zyk'],$position['yk'],2):$position['yk'];
				if($position['bs']=='bid'){
					$net = $position['total'];
				}else{
					$net = bcmul($position['total'],-1,0);
				}
				$ykArr[$position['name']]['direction'] = '';
				$ykArr[$position['name']]['net'] = isset($ykArr[$position['name']]['net'])?bcadd($ykArr[$position['name']]['net'],$net):$net;
				if($ykArr[$position['name']]['net']>0){
					$ykArr[$position['name']]['direction'] = "买涨";
				}else if ($ykArr[$position['name']]['net']<0) {
					$ykArr[$position['name']]['direction'] = "买跌";
				}
			}
		}
		//没有登陆获取uid
		//链接redis
		$platform = $this->config->item('platform');
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        //微信
        $this->load->library('session');
        $sessid = $this->session->session_id;
        $openid = $this->cache->redis->getClient()->get("$platform|WechatCallback|$sessid");
        if($openid!=''){
        	$this->load->model('user_model');
	        $whereArr = array(
	            'platform' => $platform,//平台
	            'openid' => $openid,
	        );
	        $userData = $this->user_model->getUserInfoByMulti($whereArr);
	        $assign['userData'] = $userData;
        }
        
		$assign['reg'] = isset($get['reg'])?$get['reg']:0;
		$assign['user_info'] = $user_info;
		$assign['test'] = $this->config->item('test');
		$assign['productArr'] = $productArr;
		$assign['positionArr'] = $positionArr;
		$assign['ykArr'] = $ykArr;
		$assign['socket_url'] = $this->config->item('socket_url');
		$assign['redirect'] = $redirect;
		$this->load->view('index.php',$assign);
	}


	function tixian(){
		$this->load->config('cny');
		$bankName = $this->config->item('bankArr');
		//检查是否已经注册
		$this->load->model('cny_model');
		$whereArr = array(
        	'send_status' => 0,//平台
        	//'send_amount<=' => 200,
        );
        $tmpBank = $this->cny_model->getCnyBank(array('status'=>1));
        $bankArr = array();
        foreach($tmpBank as $bank){
        	$bankArr[$bank['id']] = $bank;
        }
		$tmpData = $this->cny_model->getCnyWithdraw($whereArr);
		$html = "<style>table tr td{padding:2px}</style><table border=1><tr><td>uid</td><td>openid</td><td>提现金额</td><td>创建时间</td><td>remark</td><td>操作</td><td>省份</td><td>城市</td><td>银行</td><td>支行</td><td>卡号</td><td>姓名</td></tr>";
		if(!empty($tmpData))foreach($tmpData as $item){
			$bankData = $bankArr[$item['bank_id']];
			$html .= "<tr><td>".$item['uid']."</td><td>".$item['openid']."</td><td>".$item['send_amount']."</td><td>".$item['create_time']."</td><td>".$item['orderno']."</td><td><a href='/welcome/dotixian?orderno=".$item['orderno']."'>改为已处理</a></td><td>".$bankData['prov']."</td><td>".$bankData['city']."</td><td>".$bankName[$bankData['bank']]."</td><td>".$bankData['bank_name']."</td><td>".$bankData['card_no']."</td><td>".$bankData['card_name']."</td></tr>";
		}
		$html .= "</table>";
		echo $html;
	}

	function dotixian(){
		$get = $this->input->get();
		$orderno = trim($get['orderno']);
		//检查是否已经注册
		$this->load->model('cny_model');
		$whereArr = array(
			'orderno' => $orderno,
		);
		$tmpData = $this->cny_model->getCnyWithdraw($whereArr,1);
		var_dump($tmpData);
		if(empty($tmpData)){
			echo "订单错误！<br>";
			echo "<a href='/welcome/tixian'>返回</a>";
			die;
		}
		if($tmpData['send_status']==1){
			echo "订单已处理！<br>";
			echo "<a href='/welcome/tixian'>返回</a>";
			die;
		}
		$upArr = array(
			'send_status' => 1,
			'send_time' => date('Y-m-d H:i:s'),
		);
		$whereArr = array(
			'orderno' => $orderno,
		);
		$flag = $this->cny_model->updateWithdraw($upArr,$whereArr);
		if($flag){
			echo "订单发送成功！<br>";
			echo "<a href='/welcome/tixian'>返回</a>";
			die;
		}else{
			echo "订单发送失败！<br>";
			echo "<a href='/welcome/tixian'>返回</a>";
			die;
		}
	}


	function checkUid(){
		$get = $this->input->get();
		$uid = $get['uid'];
		$this->load->model('user_model');
		$this->load->model('cny_model');
		$this->load->model('cfd_model');
		if($uid>0){
			$where1Arr = array(
	        	'uid' => $uid,
	        );
	        $where2Arr = array(
	        	'uid' => $uid,
	        	'send_status' => 1
	        );
	        $where3Arr = array(
	        	'uid' => $uid,
	        	'flag' => 0
	        );
		}else{
			$where1Arr = array(
	        	'uid>=' => 0,
	        );
	        $where2Arr = array(
	        	'send_status' => 1
	        );
	        $where3Arr = array(
	        	'flag' => 0
	        );
		}
        $tmpUser = $this->user_model->getAllUser($where1Arr);
        $user = array();
        foreach($tmpUser as $item){
        	$user['Cny'] = bcadd($user['Cny'],$item['cny'],2);
        }
        
        $tmpDeposit = $this->cny_model->getCnyDeposit($where2Arr);
        foreach($tmpDeposit as $item){
        	$user['Deposit'] = bcadd($user['Deposit'],$item['send_amount'],2);
        }
        $tmpWithdraw = $this->cny_model->getCnyWithdraw($where1Arr);
        foreach($tmpWithdraw as $item){
        	$user['Withdraw'] = bcadd($user['Withdraw'],$item['send_amount'],2);
        }
        $tmpPosition = $this->cfd_model->getPosition($where3Arr);
        foreach($tmpPosition as $item){
        	$total_amount = bcmul(bcadd($item['num'],$item['block_num']),$item['times'],2);
        	if($item['dtype']=='cny'){
        		$user['CnyPosition'] = bcadd($user['CnyPosition'],$total_amount,2);
        	}else{
        		$user['TicketPosition'] = bcadd($user['TicketPosition'],$total_amount,2);
        	}
        }

        $tmpTradeLog = $this->cfd_model->getTradeLog($where1Arr);
        foreach($tmpTradeLog as $item){
        	if($item['dtype']=='cny'){
        		$user['CnyYk'] = bcadd($user['CnyYk'],$item['yk'],2);
        	}else{
        		$user['TicketYk'] = bcadd($user['TicketYk'],$item['yk'],2);
        	}
        }
        echo "<pre>";
        print_r($user);

	}

	function sendhb(){
		$html = "<style>table{width:100%;}table tr td{padding:20px}</style><form action='/welcome/dosendhb' method='GET'><table border=1>";
		$html .= "<tr><td width='10%'>openid:</td><td><input name='openid' style='padding:10px;width:400px'></td></tr>";
		$html .= "<tr><td>amount:</td><td><input name='amount' style='padding:10px'></td></tr>";
		$html .= "<tr><td>remark:</td><td><input name='remark' style='padding:10px'></td></tr>";
		$html .= "<tr><td colspan='2' style='margin-left:20px'><input type='submit' value='提交' style='padding:20px 40px'></td></tr>";
		$html .= "</table></form>";
		echo $html;
	}

	/**
	 */
	function dosendhb(){
		$get = $this->input->get();
		$openid = isset($get['openid'])?trim($get['openid']):'';
		$amount = isset($get['amount'])?$get['amount']:'';
		$remark = isset($get['remark'])?$get['remark']:'';
		if($openid=='' || $amount==''  || $amount<=0){
			die("输入有误！");
		}
		$this->load->library('CI_Wechat');
		$this->load->config('wxpay_config');
		// var_dump($jsSign);
		$wxconfig['appid'] = $this->config->item('appid');
		$wxconfig['mch_id'] = $this->config->item('mch_id');
		$wxconfig['apikey'] = $this->config->item('apikey');
		$wxconfig['appsecret'] = $this->config->item('appsecret');
		$wxconfig['sslcertPath'] = $this->config->item('sslcertPath');
		$wxconfig['sslkeyPath'] = $this->config->item('sslkeyPath');
		//由于此类库构造函数需要传参，我们初始化类库就传参数给他吧
		$this->load->library('WechatPay',$wxconfig);

		$nonceStr = $this->ci_wechat->generateNonceStr();

		$signArr = array(
			'nonce_str' => $nonceStr,
			'mch_billno' => $wxconfig['mch_id'].date('YmdHis').rand(1000,9999),
			'mch_id' => $wxconfig['mch_id'],
			'wxappid' => $wxconfig['appid'],
			'send_name' => '要点啥微盘',
			're_openid' => $openid,
			'total_amount' => bcmul($amount,100,0),
			'total_num' => 1,
			'wishing' => '感谢您对要点啥微盘的支持，祝您生活愉快！',
			'client_ip' => get_ip(),
			'act_name' => '微操盘红包',
			'remark' => '1606081221374521',
		);
		echo "<pre>";
		$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
		$rs = $this->wechatpay->wxHttpsRequest($url, $signArr,true);
		var_dump($rs);
		echo "<br>";
		echo "<br>";
		echo "<a href='/welcome/sendhb'>返回</a>";
	}


	public function setOP(){
		$platform = $this->config->item('platform');//平台
		$this->load->library('session');
		$sessid = $this->session->session_id;

		$openid = 'oRTybwN8-YzKk-n34z2UDuBScBW0';

		//检查是否已经注册
		$this->load->model('user_model');
		$whereArr = array(
        	'platform' => 1,//平台
        	'openid' => $openid,
        );
		$userData = $this->user_model->getUserInfoByMulti($whereArr,true);

		//链接redis
		$this->load->driver('cache');
		$this->cache->redis->is_supported();
		$this->cache->redis->getClient()->set("$platform|WechatCallback|$sessid",$openid);
		$this->cache->redis->getClient()->expire("$platform|WechatCallback|$sessid",43200);
		$_SESSION['openid'] = $openid;
		echo "设置成功";
	}

	public function createTable(){
		$get = $this->input->get();
		$table = trim($get['table']);
		$log_conn = $this->load->database('log',true);
		for($i=0;$i<10;$i++){
			$table = splitTable('cfd_log_'.$table, $i, 10);
			$sql =<<<EOD

CREATE TABLE {$table} (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '序号',
  `name` varchar(50) NOT NULL COMMENT '产品名称',
  `uid` int(10) NOT NULL COMMENT 'uid',
  `action` varchar(30) NOT NULL COMMENT '操作',
  `old` decimal(12,2) NOT NULL COMMENT '用户原有值',
  `new` decimal(12,2) NOT NULL COMMENT '用户现在值',
  `use_value` decimal(12,2) NOT NULL COMMENT '操作的值',
  `source` int(10) NOT NULL COMMENT '操作来源/去向',
  `comefrom` int(10) NOT NULL DEFAULT '1' COMMENT '来源，1:网页，2：移动客户端',
  `ip` varchar(15) NOT NULL COMMENT 'ip地址',
  `add_time` datetime NOT NULL COMMENT '操作时间',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态，0为无效，1为有效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

EOD;
		 	// var_dump($this->db);
		 	$rs = $log_conn->query($sql);
		 	var_dump($rs);
		}
	}
}
